package visualKernel;
import java.awt.GraphicsEnvironment;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import xml_smt_trans.LemmaData;
import xml_smt_trans.Pair;
import xml_smt_trans.Translator;
import xml_smt_trans.Triple;

import com.cloudgarden.layout.AnchorConstraint;
import com.cloudgarden.layout.AnchorLayout;


/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class VisualTranslator extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8633507636727102789L;
	{
		//Set Look & Feel
		try {
			javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	private JTextField jTextFieldSolverPath;
	private JCheckBox jCheckBoxShowMessagesInEditor;
	private JCheckBox jCheckBoxShowErrorMessages;
	private JCheckBox jCheckBoxShowDetails;
	private JFileChooser jDestinationChooser;
	private JLabel jLabelSolverPath;
	
	
	private ArrayList<LemmaData> lemmaDatas;
	private JCheckBox jCheckBoxOnlyView;
	private JButton jButtonProof;
	private JButton jButtonSavePreferences;
	private JButton jButtonBrowse;
	private JButton jButtonCancel;
	
	ConfigXML configXML;

	public VisualTranslator()
	{
		initGUI();		
		this.setLocation(GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint());
        getJDestinationChooser();
        this.setLocationRelativeTo(this.getFocusOwner());
               
	}
	
	public VisualTranslator(ArrayList<LemmaData> lemmas)
	{
		lemmaDatas = lemmas;
		initGUI();		
		this.setLocation(GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint());
        getJDestinationChooser();
        this.setLocationRelativeTo(this.getFocusOwner());
	}
	
	

	private void initGUI() {
		try {
			{
				getContentPane().setLayout(null);
				this.setTitle("Rodin XML to SMT Translator");
				this.setResizable(false);
				this.setPreferredSize(new java.awt.Dimension(737, 273));
				this.setDefaultCloseOperation(HIDE_ON_CLOSE);
				{
					jLabelSolverPath = new JLabel();
					AnchorLayout jLabelDestatinationFolderLayout = new AnchorLayout();
					jLabelSolverPath.setLayout(jLabelDestatinationFolderLayout);
					getContentPane().add(jLabelSolverPath, new AnchorConstraint(25, 0, 0, 19, AnchorConstraint.ANCHOR_ABS, AnchorConstraint.ANCHOR_NONE, AnchorConstraint.ANCHOR_NONE, AnchorConstraint.ANCHOR_ABS));
					jLabelSolverPath.setText("Solver Path:");
					jLabelSolverPath.setBounds(19, 25, 72, 14);
				}

				{
					jTextFieldSolverPath = new JTextField();
					getContentPane().add(jTextFieldSolverPath);
					getContentPane().add(getJButtonCancelar());
					getContentPane().add(getJButtonBrowse());
					getContentPane().add(getJButtonProof());
					getContentPane().add(getJCheckBoxShowDetails());
					getContentPane().add(getJCheckBoxShowErrorMessages());
					getContentPane().add(getJCheckBoxShowTranslatedFileInEditor());
					getContentPane().add(getJButtonSavePreferences());
					getContentPane().add(getJCheckBoxOnlyView());
					AnchorLayout jTextFieldDestinationFieldLayout = new AnchorLayout();
					jTextFieldSolverPath.setLayout(jTextFieldDestinationFieldLayout);
					jTextFieldSolverPath.setBounds(86, 22, 492, 27);
				}
			}
			this.setLocation(GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint());
			this.setLocationRelativeTo(this.getOwner());
			pack();
			
			configXML = new ConfigXML();
	        
	        jTextFieldSolverPath.setText(configXML.getSolverPath());
	        jCheckBoxOnlyView.setSelected(configXML.isNotTranslate());
	        jCheckBoxShowDetails.setSelected(configXML.isShowDetails());
	        jCheckBoxShowErrorMessages.setSelected(configXML.isShowErrorMessages());
	        jCheckBoxShowMessagesInEditor.setSelected((configXML.isShowFilesInEditor()));
	        		
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
		
	private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {
		this.setVisible(false);
	}
	
	
	
	private void jButtonProofActionPerformed(java.awt.event.ActionEvent evt) {                                                    
        if(jTextFieldSolverPath.getText().equals(""))
        {
            JOptionPane.showMessageDialog(this, "There is no Prover selected!");
            return;
        }
        try
        {
        	LemmaData ld = lemmaDatas.get(0);
        	ld.setTitle("temp");
        	lemmaDatas.set(0, ld);
        	Triple<ArrayList<String>, ArrayList<Pair<String, String>>,File> result = Translator.parseLemmas(lemmaDatas, false, null, jCheckBoxShowDetails.isSelected(), jCheckBoxShowErrorMessages.isSelected());
        	String detailsOfTranslation = "";
        	String detailsOfError = "";
        	String resultOfSolver = "";
        	if(jCheckBoxShowDetails.isSelected())
        	{
        		detailsOfTranslation = "Details of the succesfully translated Lemmas:";
              	for (int i = 0 ; i < result.getFirstElement().size() ; i++)
              	{
              		detailsOfTranslation = detailsOfTranslation + "\n" + result.getFirstElement().get(i);
              	}        	        
           
        	}
        	if(jCheckBoxShowErrorMessages.isSelected())
        	{
		    		if(result.getSecondElement() != null &&  result.getSecondElement().size() > 0)
		            {
		            	detailsOfError += "The translation finished with some erros:";
		            	for(int g = 0 ; g < result.getSecondElement().size() ; g++)
		            	{
		            		detailsOfError = detailsOfError + "\n" + result.getSecondElement().get(g).getFirstElement() + ": " + result.getSecondElement().get(g).getSecondElement();
		            	}
		            	new ArrayList<Pair<String,String>>();        			
		            } 		
		    		
        	}
	    	String[] args = new String[2];
	    	if(jCheckBoxOnlyView.isSelected() == false)
	    	{
	    		args[0] = jTextFieldSolverPath.getText();
	        	args[1] = result.getThirdElement().getPath();
	        	resultOfSolver = Translator.execProgram(args);
	        	//detailsOfTranslation = detailsOfTranslation + "\n\n" + resultOfSolver;            	
	    	}
	    	else
	    	{
	    		if(System.getProperty("os.name").startsWith("Windows"))
	    		{
	    			args[0] = "notepad";
	    		}
	    		else
	    		{
	    			args[0] = "gedit";
	    		}        		
	    		args[1] = result.getThirdElement().getPath();
	    		Translator.execProgram(args);
	    	}
	    	if(jCheckBoxShowMessagesInEditor.isSelected() == false)
	    	{
	       		JOptionPane.showMessageDialog(this, detailsOfTranslation + "\n\n" + detailsOfError + "\n\n" + resultOfSolver);
	    	}
	    	else
	    	{
	    		File statsFile = File.createTempFile("statsFile", ".tmp",new File(System.getProperty("user.dir")));
	    		PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(statsFile)));
				if(!detailsOfTranslation.isEmpty())
				{
					out.println(detailsOfTranslation);
					out.println("");
					out.println("-------");
					out.println("-------");
					out.println("");
				}
	    		if(!detailsOfError.isEmpty())
	    		{
	    			out.println(detailsOfError);
					out.println("");
					out.println("-------");
					out.println("-------");
					out.println("");
	    		}
				out.println(resultOfSolver);
				
				
				out.close();
				if(System.getProperty("os.name").startsWith("Windows"))
	    		{
	    			args[0] = "notepad";
	    		}
	    		else
	    		{
	    			args[0] = "gedit";
	    		}        		
				args[1] = statsFile.getPath();
				Translator.execProgram(args);
	    	}		    	
        } catch (ParserConfigurationException e) {
		//e.printStackTrace();
		JOptionPane.showMessageDialog(this, "This PO could not be parsed due to bad configuration of the parser","Parser Exception", JOptionPane.ERROR_MESSAGE);//,  MessageDialog.ERROR);
	} catch (SAXException e) {
		//e.printStackTrace();
		JOptionPane.showMessageDialog(this, "This PO could not be parsed due to bad structure of the file","SAX Exception",JOptionPane.ERROR_MESSAGE);//MessageDialog.ERROR);
	} catch (IOException e) {
		//e.printStackTrace();
		JOptionPane.showMessageDialog(this, "This PO could not be parsed due to IO Problem.","IO Exception",JOptionPane.ERROR_MESSAGE);//MessageDialog.ERROR);
	}	
}

	
	
	
	private JFileChooser getJDestinationChooser() {
		if(jDestinationChooser == null) {
			jDestinationChooser = new JFileChooser();//AcaoSimples.getWorkspaceDir());
			jDestinationChooser.setFileSelectionMode(javax.swing.JFileChooser.FILES_ONLY);
			if(System.getProperty("os.name").startsWith("Windows"))
			{
				FileNameExtensionFilter fl = new FileNameExtensionFilter("executable (*.exe)", "exe");
				jDestinationChooser.addChoosableFileFilter(fl);
			}
			 
		}	
		return jDestinationChooser;
	}
	
	private JButton getJButtonCancelar() {
		if(jButtonCancel == null) {
			jButtonCancel = new JButton();
			jButtonCancel.setText("Cancel");
			jButtonCancel.setBounds(595, 157, 133, 40);
			jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
	            public void actionPerformed(java.awt.event.ActionEvent evt) {
	                jButtonCancelActionPerformed(evt);
	            }
	        });
		}
		return jButtonCancel;
	}	
	
	
	
	private void jButtonSetSolverExeActionPerformed(java.awt.event.ActionEvent evt)
	{
		int returnVal = jDestinationChooser.showSaveDialog(this);
		if(returnVal == JFileChooser.APPROVE_OPTION)
		{
			jTextFieldSolverPath.setText(jDestinationChooser.getSelectedFile().getPath());
			//nameOfFile = jDestinationChooser.getSelectedFile().getName();
		}
	}
	
	private JButton getJButtonProof() {
		if(jButtonProof == null) {
			jButtonProof = new JButton();
			jButtonProof.setText("Proof!");
			jButtonProof.setBounds(594, 57, 133, 40);
			jButtonProof.addActionListener(new java.awt.event.ActionListener() {
	            public void actionPerformed(java.awt.event.ActionEvent evt) {
	                jButtonProofActionPerformed(evt);
	            }
	        });
		}
		return jButtonProof;
	}
	
	private JButton getJButtonBrowse() {
		if(jButtonBrowse == null) {
			jButtonBrowse = new JButton();
			jButtonBrowse.setText("Browse");
			jButtonBrowse.setBounds(594, 17, 133, 31);
			jButtonBrowse.addActionListener(new java.awt.event.ActionListener() {
	            public void actionPerformed(java.awt.event.ActionEvent evt) {
	                jButtonSetSolverExeActionPerformed(evt);
	            }
	        });
		}
		return jButtonBrowse;
	}
	
	

	private JCheckBox getJCheckBoxShowDetails() {
		if(jCheckBoxShowDetails == null) {
			jCheckBoxShowDetails = new JCheckBox();
			jCheckBoxShowDetails.setText("Show Details");
			jCheckBoxShowDetails.setBounds(19, 66, 114, 23);
		}
		return jCheckBoxShowDetails;
	}
	
	private JCheckBox getJCheckBoxShowErrorMessages() {
		if(jCheckBoxShowErrorMessages == null) {
			jCheckBoxShowErrorMessages = new JCheckBox();
			jCheckBoxShowErrorMessages.setText("Show Error Messages");
			jCheckBoxShowErrorMessages.setBounds(19, 106, 250, 23);
		}
		return jCheckBoxShowErrorMessages;
	}
	
	private JCheckBox getJCheckBoxShowTranslatedFileInEditor() {
		if(jCheckBoxShowMessagesInEditor == null) {
			jCheckBoxShowMessagesInEditor = new JCheckBox();
			jCheckBoxShowMessagesInEditor.setText("Open messages in a text editor");
			jCheckBoxShowMessagesInEditor.setBounds(20, 143, 202, 23);
		}
		return jCheckBoxShowMessagesInEditor;
	}
	
	private JButton getJButtonSavePreferences() {
		if(jButtonSavePreferences == null) {
			jButtonSavePreferences = new JButton();
			jButtonSavePreferences.setText("Save Preferences");
			jButtonSavePreferences.setBounds(594, 108, 133, 38);
			jButtonSavePreferences.addActionListener(new java.awt.event.ActionListener() {
	            public void actionPerformed(java.awt.event.ActionEvent evt) {
	                jButtonSavePreferencesActionPerformed(evt);
	            }
	        });
			
			
		}
		return jButtonSavePreferences;
	}
	
	private void jButtonSavePreferencesActionPerformed(java.awt.event.ActionEvent evt)
	{
		configXML.setNotTranslate(jCheckBoxOnlyView.isSelected());
		configXML.setShowDetails(jCheckBoxShowDetails.isSelected());
		configXML.setShowErrorMessages(jCheckBoxShowErrorMessages.isSelected());
		configXML.setShowFilesInEditor(jCheckBoxShowMessagesInEditor.isSelected());
		configXML.setSolverPath(jTextFieldSolverPath.getText());
		configXML.updateInfo();
	}
	
	
	
	private JCheckBox getJCheckBoxOnlyView() {
		if(jCheckBoxOnlyView == null) {
			jCheckBoxOnlyView = new JCheckBox();
			jCheckBoxOnlyView.setText("Apenas mostrar o arquivo traduzido");
			jCheckBoxOnlyView.setBounds(333, 66, 245, 22);
		}
		return jCheckBoxOnlyView;
	}

}
